<template>
  <div class="login">
    <header :style="headerHeight">
      <div class="container">
        <div class="loginHead">
          <div class="headLeft">
            <span>NEWEWT</span>
          </div>
          <div class="headRight">
            <span @click="jumpUrl('/home')"><i class="el-icon-s-home"></i> 返回首页</span>
            <span @click="jumpUrl('/service-center')"><i class="el-icon-question"></i> 联系客服</span>
<!--            <span><button @click="messageBox">按钮</button></span>-->
          </div>
        </div>
      </div>
    </header>
    <main :style="mainHeight">
      <div class="box"></div>
      <div class="login">
        <div class="container">
          <div class="loginBox">
            <div class="loginType">
              <div
                v-for="(item,index) in position.typeList"
                :key="index"
                @click="checkLoginType(item)"
                :class="item.flag?'checked':''"
                id="item.id">
                {{item.name}}
              </div>
            </div>
            <div class="slideBlock">
              <div :style="position.block" class="block"></div>
            </div>
            <div class="content">
              <div class="contentBox">
                <div :style="position.content" class="codeContentBox">
                  <div class="codeBox">
                    <el-form v-if="position.content.left==='0'" :model="codeRuleForm" :rules="rules" ref="ruleForm">
                      <el-form-item prop="cardNumber">
                        <el-input
                          type="text"
                          v-model="codeRuleForm.cardNumber"
                          placeholder="请输入学校提供的账号/手机号"
                          prefix-icon="el-icon-mobile-phone"
                          @keypress.native.enter="toLogin('ruleForm')"
                          autocomplete="off"></el-input>
                      </el-form-item>
                      <el-form-item prop="password">
                        <el-input
                          type="password"
                          v-model="codeRuleForm.password"
                          placeholder="请输入密码"
                          prefix-icon="el-icon-lock"
                          @focus="pwdFalse=false"
                          @keypress.native.enter="toLogin('ruleForm')"
                          autocomplete="off"></el-input>
                        <p class="pwdVerify"><span v-show="pwdFalse" v-text="pwdFalseText"></span></p>
                      </el-form-item>
                    </el-form>
                  </div>
                  <div class="smsCodeBox">
                    <el-form v-if="position.content.left!=='0'" :model="smsCodeRuleForm" :rules="rules" ref="ruleForm">
                      <el-form-item prop="phoneNumber">
                        <el-input
                          type="text"
                          v-model="smsCodeRuleForm.phoneNumber"
                          placeholder="请输入手机号"
                          prefix-icon="el-icon-mobile-phone"
                          @focus="phoneFalse=false"
                          @blur="phoneType"
                          autocomplete="off">
                        </el-input>
                        <p class="verify"><span v-show="phoneFalse" v-text="phoneRegistered?phoneRegistered:phoneRule"></span></p>
                      </el-form-item>
                      <el-form-item prop="smsCode">
                        <el-input
                          type="text"
                          v-model="smsCodeRuleForm.smsCode"
                          placeholder="请输入验证码"
                          prefix-icon="el-icon-circle-check"
                          autocomplete="off"
                          @blur="smsCodeType"
                          @focus="smsCodeFalse=false"
                          style="width: 56%;">
                        </el-input>
                        <el-button
                          @click="getSmsCode"
                          :disabled="isDisabled"
                          class="getSmsCode">
                          {{getSmsCodeText}}
                        </el-button>
                        <p class="smsCodeVerify"><span v-show="smsCodeFalse" v-text="smsCodeVerify"></span></p>
                      </el-form-item>
                    </el-form>
                  </div>
                </div>
              </div>
            </div>
            <div class="aside">
              <div class="remCode">
                <el-checkbox v-model="rememberCode">记住密码</el-checkbox>
              </div>
              <div class="forgetCode">
                <a @click="jumpUrl('/forget')">忘记密码?</a>
              </div>
            </div>
            <div class="btn">
              <el-button type="primary" @click="toLogin('ruleForm')">登录</el-button>
            </div>
            <div class="aside">
              <div class="register">
                <a @click="jumpUrl('/register')">立即注册</a>
              </div>
              <div class="forgetCode">
                <a >购买会员</a>
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>
    <aside>
      <el-dialog
        :visible.sync="captchaDialog"
        :close-on-click-modal="false"
        append-to-body
        :center="true"
        :show-close="false"
        z-index="500"
        width="360px"
      >
        <Captcha
          v-model="captchaDialog"
          width="300px"
          height="240px"
          :max-dot="maxDot"
          :image-base64="imageBase64"
          :thumb-base64="thumbBase64"
          :error-prompt="errorPrompt"
          @close="handleCloseEvent"
          @refresh="handleRefreshEvent"
          @confirm="handleConfirmEvent"
        ></Captcha>
      </el-dialog>
    </aside>
  </div>
</template>

<script>
    import { userLogin, getSmsCode, SmsCodeExist } from '../../api/user.js'
    import { getCaptcha, checkCaptcha } from '../../api/captcha.js'
    import { getAgreement, checkExist, regSmsCode, confirmRegister } from '../../api/register.js'
    import Captcha from './register/captcha/captcha.vue'
    export default {
        name: "login",
        data() {
            return {
                pageHeight: '',
                headerHeight: {
                    height: ''
                },
                mainHeight: {
                    height: ''
                },
                // 页面动画
                position: {
                    typeList: [
                        {name: '密码登录', id: 'code', flag: true},
                        {name: '验证码登录', id: 'smsCode', flag: false}
                    ],
                    block: { left: '55px' },
                    content: { left: '0' }
                },
                loginType: 'code',
                // 获取验证码倒计时
                getSmsCodeText: '获取验证码',
                count: null,
                timer: null,
                isDisabled: false,
                // 是否记住密码
                rememberCode: true,
                // 密码登录规则
                pwdFalse: false,
                pwdFalseText: '',
                codeRuleForm: {
                    cardNumber: '',
                    password: '',
                },
                smsCodeRuleForm: {
                    phoneNumber: '',
                    smsCode: null,
                },
                rules: {
                    cardNumber: [
                        { required: true, message: '请输入学校提供的账号/手机号', trigger: 'blur' },
                        // { min: 5, max: 12, message: '账号/手机号错误', trigger: 'blur' }
                    ],
                    password: [
                        { required: true, message: '请输入密码', trigger: 'blur' },
                        { min: 6, max: 16, message: '密码长度6-16字符', trigger: 'blur' }
                    ],
                },
                // 提示
                phoneFalse: false,
                phoneRegistered: '',  // 手机是否注册
                phoneRule: '手机号码不能为空',
                // 点选验证组件
                captchaDialog: false,
                maxDot: 5,
                imageBase64: '',
                thumbBase64: '',
                captchaKey: '',  // 成功获取点选验证码返回的key
                errorPrompt: '',   // 点选验证返回的错误信息
                captchaToken: '',  // 点选验证返回的token
                smsCodeFalse: false,
                smsCodeVerify: '验证码不能为空',
            }
        },
        created() {

        },
        components: {
            Captcha
        },
        mounted() {
            this.getPageHeight();
            window.onresize = () => {
                this.getPageHeight();
            };
        },
        methods: {
            messageBox() {
                this.$my_message('这是一个warning','warning');
            },
            // 获取页面高度
            getPageHeight() {
                this.pageHeight = document.documentElement.clientHeight;  // 页面高度
                this.headerHeight.height = this.pageHeight * 0.2 + 'px';
                this.mainHeight.height = this.pageHeight * 0.7 + 'px';
                // console.log(this.pageHeight);
                // let headerHeight = document.getElementsByTagName('header')[0].offsetHeight;  // header高度
            },
            // 跳转页面
            jumpUrl(router) {
                this.$router.push(router)
            },
            // 清空验证规则
            clearRules() {
               this.pwdFalse = false;
               this.phoneFalse = false;
               this.smsCodeFalse = false;
            },
            // 选择登录方式
            checkLoginType(item) {
                this.clearRules();
                if(!item.flag) {
                    this.position.typeList.forEach(type => {
                        type.flag = !type.flag;
                    });
                    if(item.id==='code') {
                        this.loginType = item.id;
                        this.position.block = { left: '55px' };
                        this.position.content = { left: '0' }
                    }else{
                        this.loginType = item.id;
                        this.position.block = { left: '175px' };
                        this.position.content = { left: '-256px' }
                    }
                }
            },
            /** 手机验证码登录 **/
            // 手机号验证
            phoneType() {
                let re = /^1[3456789]{1}\d{9}$/;
                let str = this.smsCodeRuleForm.phoneNumber;
                if(re.test(str)){
                    this.phoneFalse = false;
                }else {
                    if(str.length>0) {
                        this.phoneRule = '手机号不符';
                        this.phoneFalse = true;
                    }else{
                        this.phoneRule = '手机号不能为空';
                        this.phoneFalse = true;
                    }
                }
            },
            smsCodeType() {
                let str = this.smsCodeRuleForm.smsCode;
                if(str) {
                    this.smsCodeFalse = false;
                }else{
                    this.smsCodeFalse = true;
                }
            },
            // 关闭(点选验证码)
            handleCloseEvent() {
                this.captchaDialog = false;
                this.errorPrompt = '';
            },
            // 刷新(点选验证码)
            async handleRefreshEvent() {
                this.errorPrompt = '';
                const res = await getCaptcha();
                if(res.status===200) {
                    this.captchaKey = res.data.captcha_key;
                    this.imageBase64 = res.data.image_base64;
                    this.thumbBase64 = res.data.thumb_base64;
                    if(this.imageBase64 && this.thumbBase64) {
                        this.captchaDialog = true;
                    }
                }
            },
            // 确认(点选验证码)
            async handleConfirmEvent(dots) {
                this.errorPrompt = '';
                let dotArr = [];
                dots.forEach(dot => {
                    dotArr.push(dot.x, dot.y)
                });
                const res = await checkCaptcha({
                    "dots": dotArr.join(','),
                    "key": this.captchaKey,
                });
                if (res.data.code===200){
                    // 验证通过，执行下面接口
                    console.log(res.data);
                    this.captchaToken = res.data.data.captchaToken;
                    this.captchaDialog = false;
                    // 校验手机号是否注册
                    const isRegister = await checkExist({
                        "mobileAccount": this.smsCodeRuleForm.phoneNumber,
                        "captchaToken": this.captchaToken
                    });
                    if(isRegister.data.status) {
                        // 如果手机已经注册做出提示
                        this.phoneRegistered = '该手机号已经注册';
                        this.phoneFalse = true;   // 错误提示
                    }else{
                        // 手机未注册，执行后面接口
                        const smsCode = await getSmsCode({
                            "mobile": this.smsCodeRuleForm.phoneNumber,
                            "token": this.captchaToken
                        });
                        if(smsCode.data.status) {
                            this.captchaToken = smsCode.data.data.checkToken;
                            // 获取验证码，倒计时
                            let i = 120;
                            let timer = setInterval(() => {
                                this.getSmsCodeText = '获取验证码' + i + 's';
                                i--;
                                if (i < 0) {
                                    clearInterval(timer);
                                    this.getSmsCodeText = '获取验证码';
                                }
                            }, 1000);
                        }
                    }
                }else{
                    //如果验证错误或未点选则弹出对话框或错误提示
                    this.errorPrompt = res.data.msg;
                    //并刷新下验证码让用户重新选择
                }
            },
            // 获取验证码
            async getSmsCode() {
                // 点选验证
                this.phoneType();
                if(!this.phoneFalse) {
                    // 获取点选验证码
                    const captchaCode = await getCaptcha();
                    if(captchaCode.status===200) {
                        this.captchaKey = captchaCode.data.captcha_key;
                        this.imageBase64 = captchaCode.data.image_base64;
                        this.thumbBase64 = captchaCode.data.thumb_base64;
                        if(this.imageBase64 && this.thumbBase64) {
                            this.captchaDialog = true;
                        }
                    }
                }
            },
            /** 登录 **/
            toLogin(formName) {
                // base64加密
                let Base64 = require('js-base64').Base64;
                this.codeRuleForm.password = Base64.encode(this.codeRuleForm.password);
                console.log('加密后密码'+this.codeRuleForm.password);
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        // 判断是密码登录还是短信验证码登录
                        if(this.loginType==='code') {
                            // 密码登录
                            userLogin({
                                "userName": this.codeRuleForm.cardNumber,
                                "password": this.codeRuleForm.password,
                                "client": 'pc'
                            }).then(res => {
                                if(res.data.status) {
                                    sessionStorage.setItem('token',JSON.stringify(res.data.data.token));
                                    sessionStorage.setItem('userId',JSON.stringify(res.data.data.userId));
                                    this.$router.push({
                                        path: '/plan'
                                    })
                                }else{
                                    this.pwdFalseText = res.data.msg;
                                    this.pwdFalse = true;
                                }
                            });
                        }else {
                            // 验证码登录
                            console.log(this.smsCodeRuleForm);
                            // 判断是否填写手机号及验证码，符合规则
                            if(this.smsCodeRuleForm.smsCode) {
                                if(this.smsCodeRuleForm.phoneNumber) {
                                    if(this.smsCodeRuleForm.phoneNumber.length!==11) {
                                        this.phoneRule = '手机号不符';
                                        this.phoneFalse = true;
                                    }else{
                                        SmsCodeExist({
                                            "mobile": this.smsCodeRuleForm.phoneNumber,
                                            "smsCode": this.smsCodeRuleForm.smsCode,
                                            "token": this.captchaToken,
                                            "client": 'pc'
                                        }).then(res => {
                                            if(res.data.status) {
                                                sessionStorage.setItem('token',JSON.stringify(res.data.data.token));
                                                sessionStorage.setItem('userId',JSON.stringify(res.data.data.userId));
                                                this.$router.push({
                                                    path: '/plan'
                                                })
                                            }
                                        })
                                    }
                                }else{
                                    this.phoneRule = '手机号不能为空';
                                    this.phoneFalse = true;
                                }
                            }else{
                               this.smsCodeFalse = true;
                            }
                        }
                    } else {
                        // console.log('error submit!!');
                        return false;
                    }
                });
            },
        }
    }
</script>

<style scoped lang="scss">
  @import "../../styles/common";
  // header
  header{
    max-height: 90px;
    .loginHead{
      display: flex;
      justify-content: space-between;
      /*border: 1px solid green;*/
      height: 90px;
      .headLeft{
        line-height: 90px;
        width: 50%;
        span{
          font-size: 1.6rem;
          color: #2e86ff;
        }
      }
      .headRight{
        padding-top: 65px;
        span{
          padding: 0 10px;
          cursor: pointer;
        }
      }
    }
  }
  // main
  main{
    .box{
      height: 10%;
      box-shadow: 0 0 8px #ddd inset;
    }
    .login{
      // min-height: 528px;
      height: 90%;
      background-image: url(../../assets/img/login-bg.jpg);
      background-repeat: no-repeat;
      .container{
        position: relative;
        height: 100%;
      }
      .loginBox{
        border: 1px solid #f5f5f5;
        width: 320px;
        height: 360px;
        position: absolute;
        top: 50%;
        right: 5px;
        transform: translate(-5px, -50%);
        background-color: #fff;
        box-shadow: 0 0 2px #f2f2f2;
        border-radius: 4px;
        .loginType{
          /*border: 1px solid red;*/
          display: flex;
          margin-top: 50px;
          padding-left: 20px;
          div{
            width: 100px;
            text-align: center;
            font-size: 1.1rem;
            margin-right: 20px;
            cursor: pointer;
          }
          .checked{
            color: #2e86ff;
          }
        }
        .slideBlock{
          margin-top: 4px;
          position: relative;
          width: 100%;
          .block{
            width: 30px;
            height: 2px;
            background-color: #2e86ff;
            position: absolute;
            left: 175px;    // 55px
            top: 0;
            transition: all 0.5s;
          }
        }
        .content{
          /*border: 1px solid red;*/
          margin-top: 20px;
          .contentBox{
            height: 150px;
            width: 256px;
            margin: auto;
            position: relative;
            overflow: hidden;
            .codeContentBox{
              display: flex;
              flex-wrap: nowrap;
              width: 512px;
              height: 100%;
              position: absolute;
              top: 0;
              left: 0;
              transition: all 0.3s;
            }
            .codeBox,.smsCodeBox{
              width: 256px;
              height: 100%;
              .el-form-item{
                /*border: 1px solid red;*/
                position: relative;
                p.verify,p.smsCodeVerify,p.pwdVerify{
                  position: absolute;
                  bottom: -8px;
                  height: 14px;
                  span{
                    color: #f00;
                    font-size: 0.8rem;
                  }
                }
              }
              .el-input{
                margin-top: 10px;
              }
              .getSmsCode{
                padding: 12px 0;
                background-color: #409eff;
                border: 1px solid #DCDFE6;
                color: #fff;
                width: 40%;
                margin-left: 10px;
              }
            }
          }
        }
        .aside{
          display: flex;
          justify-content: space-between;
          width: 80%;
          margin: 0 auto 10px;
          a{
            color: #2e86ff;
            cursor: pointer;
          }
        }
        .btn{
          text-align: center;
          margin-bottom: 10px;
          .el-button{
            width: 80%;
          }
        }
      }
    }
  }
</style>